package com.spa.infrastructure.config;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.spa.infrastructure.enums.dict.base.RequestSourceEnum;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @author Duke_yzl
 * @date 20230615.01
 * @describe：
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {


    // 注册 Sa-Token 拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能,并添加校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handler -> {


            // 权限校验 -- 不同模块校验不同权限
            SaRouter.match("/" + RequestSourceEnum.Member.getCode() + "/**", r -> notLoginException(RequestSourceEnum.Member));
            SaRouter.match("/" + RequestSourceEnum.Massagist.getCode() + "/**", r -> notLoginException(RequestSourceEnum.Massagist));
            SaRouter.match("/" + RequestSourceEnum.Shop.getCode() + "/**", r -> notLoginException(RequestSourceEnum.Shop));
            SaRouter.match("/" + RequestSourceEnum.Admin.getCode() + "/**", r -> notLoginException(RequestSourceEnum.Admin));

            List<String> list = Arrays.asList(
                    "/favicon.ico",
                    "/MP_verify_GII6Pr9qe7qm70AN.txt",
                    "/wx/refundNotify",
                    "/wx/payNotify",
                    "/wx/wxpay_success",
                    "/wx/payNotifyV3",
                    "/",
                    "/**/*.css",
                    "/**/*.js",
                    "/profile/**",
                    "/*.html",
                    "/**/*.html",
                    "/webjars/**",
                    "/v3/**",
                    "/oauth/**",
                    "/error");
            // 指定一条 match 规则
            SaRouter.match("/**")
                    .notMatch(list)
                    .check(r -> StpUtil.checkLogin());

        })).addPathPatterns("/**");



    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public void notLoginException(RequestSourceEnum requestSourceEnum){
        if(StpUtil.hasPermission(requestSourceEnum.getCode()) == false){
            throw new NotPermissionException("【用户来源：" + StpUtil.getLoginDevice() + "】");
        }
    }

}